package org.wanxian.stores.db;

import java.util.ArrayList;

import org.wanxian.stores.model.StoreCollect;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class StoreCollectDao {

	private DatabaseOpenHelper dbHelper;
	private static final String TABLE_NAME = "prodeuctInIndent";
	
	public StoreCollectDao(Context context) {
		dbHelper = new DatabaseOpenHelper(context);
	}
	
	public int insert(StoreCollect storeCollect) {
		StoreCollect bef = queryById(storeCollect.getId());
		if(bef != null) {
			deleteById(bef.getId());
		}
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("userId", storeCollect.getUserId());
		values.put("storeId", storeCollect.getStoreId());
		int id = (int) db.insert(TABLE_NAME, null, values);
		return id;
	}
	
	public int update(StoreCollect storeCollect) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues value = new ContentValues();
		value.put("userId", storeCollect.getUserId());
		value.put("storeId", storeCollect.getStoreId());
		int index = (int) db.update(TABLE_NAME, value, "id = ?", new String[]{String.valueOf(storeCollect.getId())});
		db.close();
		return index;
	}
	
	public void deleteById(int id) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(TABLE_NAME, "id = ?", new String[] {String.valueOf(id)});
		db.close();
	}
	
	public void deleteByUserIdAndStoreId(int userId, int storeId) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(TABLE_NAME, "userId = ? and storeId = ?", new String[] {String.valueOf(userId), String.valueOf(storeId)});
		db.close();
	}
	
	public StoreCollect queryById(int id) {
		StoreCollect storeCollect = null;
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, "id = ?", new String[]{String.valueOf(id)}, null, null, null);
		while(cursor.moveToNext()) {
			int userId = cursor.getInt(cursor.getColumnIndex("userId"));
			int storeId = cursor.getInt(cursor.getColumnIndex("storeId"));
			storeCollect = new StoreCollect(id, userId, storeId);
		}
		cursor.close();
		db.close();
		return storeCollect;
	}
	
	public ArrayList<StoreCollect> queryAllByUserId(int userId) {
		ArrayList<StoreCollect> list = new ArrayList<StoreCollect>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, "userId = ?", new String[]{String.valueOf(userId)}, null, null, null);
		while(cursor.moveToNext()) {
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			int storeId = cursor.getInt(cursor.getColumnIndex("storeId"));
			StoreCollect storeCollect = new StoreCollect(id, userId, storeId);
			list.add(storeCollect);
		}
		cursor.close();
		db.close();
		return list;
	}
	
	
}
